<template>
	<view class="blessingPage">
		<block v-if="isVoice==2">
			<view>
				<view class="audio_style" :style="{justifyContent:(isloading? 'center':'space-around')}">
					<!-- 开始录音 -->
					<view class="circle_style c_record" v-if="!isloading" @tap="startRecord">
						<uni-icons type="mic-filled" size="20" color="#fff"></uni-icons>
						<text class="audio_text">录音</text>
					</view>

					<!-- 完成录音 -->
					<view class="circle_style c_save"  v-else @tap="endRecord">
						<uni-icons type="checkbox-filled" size="20" color="#fff"></uni-icons>
						<text class="audio_text">结束</text>
					</view>
					
					<!-- 选择录音 -->
					<view class="select_audio">
						<view class="circle_style c_save" v-if="!isloading" @tap="selectAudio">
							<uni-icons type="upload-filled" size="20" color="#fff"></uni-icons>
							<text class="audio_text">选择录音</text>
						</view>
						<!-- <button @click="deleteItem" type="default" size="mini">取消</button> -->
					</view>
				</view>

				<!-- <view v-if="dataInfo"> -->
				<view class="audio_content" v-if="audio_tmp_src">
					<view class="audio_pay">
						<image class="audio_pic" src="https://www.xzthealth.com/Public/MallSmallApp/audio_pic.png"></image>
						<image class="audio_play" @tap="playVoice" v-if="isPlay"
							src="../../../static/images/audio_play_start.png"></image>
						<image class="audio_play" @tap="stopPlay" v-else
							src="../../../static/images/audio_play_end.png"></image>
					</view>
					<view v-if="dataInfo.name" class="audio_info">
						<text class="audio_name">录音名称: {{dataInfo.name?dataInfo.name:'暂无信息'}}</text>
						<text>录音大小: {{dataInfo.size?dataInfo.size:'暂无信息'}}</text>
						<text>录音时间: {{audio_length?audio_length + 's':'暂无信息'}}</text>
					</view>
				</view>

				<view class="audio_style">
					<!-- 保存录音 -->
					<view class="circle_style c_play" v-if="(audio_tmp_src && (audio_tmp_src != audio_modle_src || !audio_modle_src))"
						@click="submitBlessing(2)">
						<uni-icons type="upload-filled" size="20" color="#fff"></uni-icons>
						<text class="audio_text">保存</text>
					</view>

					<!-- 删除录音 -->
					<view class="circle_style c_del" v-if="audio_modle_src" @click="deleteItem(2,isVoice)">
						<uni-icons size="20" type="trash-filled" color="#fff"></uni-icons>
						<text class="audio_text">删除</text>
					</view>
				</view>
			</view>


		</block>



		<block v-else>
			<view class="video_item">
				<view @tap="test" class="select_video c_record">选择视频</view>
				<view class="select_video c_save" v-if="(video_tmp_src && (video_tmp_src != video_modle_src || !video_modle_src))"
					@click="submitBlessing(1)">
					保存视频
				</view>
				<view v-if="video_modle_src" class="select_video c_del" @click="deleteItem(1,isVoice)">
					删除视频
				</view>
			</view>
			<view class="tmpvideo" v-if="video_tmp_src">
				<video :src="video_tmp_src"></video>
			</view>
		</block>


		<view v-if="isVoice==2 && isloading" class="luzhi_style">
			<block>
				录制中<span class="loading">...</span>
			</block>
		</view>

	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();

	var app = getApp().globalData;
	
	import {
		uploadVideo
	} from '@/utils/uploadvideo.js'
	// import uniIcons from '@/components/uni-icons/icons.vue'
	import {
		changeLimt
	} from '@/utils/changeLimt.js'
	import {
		format_time
	} from '@/utils/util.js'
	// innerAudioContext.autoplay = true;
	export default {
		data() {
			return {
				text: 'uni-app',
				// voicePath: '',		
				audio_tmp_src: '', // 音频临时路径
				audio_modle_src: '', // 音频正式路径
				video_tmp_src: '', // 视频临时文件
				video_modle_src: '', // 视频正式文件
				tmpSrc: '', // 文件临时路径
				modleSrc: '', // 文件完整路径
				dataInfo: {
					savename: '',
					storage_type: '',
					name: '',
					size: '',
				},
				isVoice: 1, //  1视频2音频
				audio_length: '', // 音频时长
				isloading: false,
				isCanPlay: false,
				isPlay: true,
				isSave: false,
				tabs: [{
						name: '录制音频',
					},
					{
						name: '上传音频',
					},
				],
				defaultIndex: 0,
				audio_params: {},
				blessData: {}
			}
		},
		onLoad(options) {
			console.log(options,'options')
			let isVoice = options.isVoice
			let blessData = options.blessData
			if (isVoice) {
				this.isVoice = isVoice
			}
			if (blessData) {
				this.blessData = JSON.parse(blessData)
				this.tmpSrc = this.blessData.address
				this.modleSrc = this.blessData.address
				if (this.blessData.ext == 'mp3') {
					this.audio_tmp_src = this.blessData.address
					this.audio_modle_src = this.blessData.address
				} else {
					this.video_tmp_src = this.blessData.address
					this.video_modle_src = this.blessData.address
				}
				this.$set(this.dataInfo, 'storage_type', this.blessData.storage_type)
				this.$set(this.dataInfo, 'savename', this.blessData.address)
			}
			let blessDataInfo = uni.getStorageSync('blessData')
			if (blessDataInfo) {
				blessDataInfo = JSON.parse(blessDataInfo)
				this.$set(this.dataInfo, 'savename', blessDataInfo.url);
				this.$set(this.dataInfo, 'storage_type', blessDataInfo.storageType);
				if (blessDataInfo.ext == 'mp3') {
					this.audio_tmp_src = blessDataInfo.address
					this.audio_modle_src = blessDataInfo.address
					this.dataInfo.size = blessDataInfo.size
					this.dataInfo.name = blessDataInfo.name
				} else {
					this.video_tmp_src = blessDataInfo.address
					this.video_modle_src = blessDataInfo.address
				}
				this.modleSrc = blessDataInfo.address
				this.tmpSrc = blessDataInfo.address
			}


			let self = this;
			recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				console.log(res.tempFilePath)
				self.audio_tmp_src = res.tempFilePath;
			});
		},
		onShow() {

		},
		watch: {
			tmpSrc: function(newVal, oldVal) {
				console.log(newVal, oldVal)
			},
		},

		methods: {
			tabClick(index) {
				this.defaultIndex = index
			},
			//选择音频
			selectAudio() {
				let _this = this
				uni.chooseMessageFile({
					success: function(res) {
						
						if (res.errMsg == 'chooseMessageFile:ok') {
							let tempFiles = Object.assign({}, res.tempFiles[0])
							if(tempFiles.type == 'video') {
								uni.showToast({
									title: '该文件为MP4格式,请通过上传视频方式上传',
									icon: 'none'
								})
								return;
							}
							tempFiles.size = changeLimt(tempFiles.size)
							// tempFiles.time = format_time(tempFiles.time)
							_this.dataInfo = Object.assign({}, tempFiles)
							_this.$set(_this.dataInfo,'name',tempFiles.name)
							_this.$set(_this.dataInfo,'size',tempFiles.size)
							_this.audio_tmp_src = tempFiles.path
						}
					}
				})
			},
			startRecord() {
				console.log('开始录音');
				this.isloading = true
				this.isPlay = true
				const options = {
					duration: 60000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
					sampleRate: 16000, //采样率
					numberOfChannels: 1, //录音通道数
					encodeBitRate: 96000, //编码码率
					format: 'mp3', //音频格式，有效值 aac/mp3
					frameSize: 50, //指定帧大小，单位 KB
				}
				recorderManager.start(options);
			},
			endRecord() {
				this.isloading = false
				console.log('录音结束');
				recorderManager.stop();
				this.isCanPlay = true
			},
			playVoice() {
				console.log('播放录音');
				// this.tmpSrc = 'wxfile://tmp_dd29fde7ab24a1e93e843ad09570177f8c0b918d4653ee60.mp3'
				if (this.audio_tmp_src) {
					innerAudioContext.src = this.audio_tmp_src;
					this.isPlay = false
					innerAudioContext.play()
					innerAudioContext.onPlay(() => {
						innerAudioContext.onTimeUpdate(() => {
							console.log(innerAudioContext.duration);
						})
						setTimeout(() => {
							this.audio_length = innerAudioContext.duration
						}, 1000)
					})
					innerAudioContext.onEnded(() => {
						this.isPlay = true
					})
				}
			},

			// 播放暂停
			stopPlay() {
				innerAudioContext.pause()
				this.isPlay = true
			},
			// 拍摄视频
			test: function() {
				var self = this;
				uni.chooseVideo({
					count: 1,
					compressed: false,
					sourceType: ['camera', 'album'],
					success: function(res) {
						if (res.errMsg == 'chooseVideo:ok') {
							self.video_tmp_src = res.tempFilePath;
							self.submitBlessing(2)
						}
					}
				});
			},

			/// 保存语音/视频
			submitBlessing(type) {
				let baseUrl = getApp().globalData.XcxData.siteBaseUrl
				uploadVideo({
					url: `/Blessing/Applets/uploadBlessing`,
					fileType: type == 2 ? 'audio' : 'video',
					path: type == 2 ? this.audio_tmp_src : this.video_tmp_src,
					formData: {},
					name: 'file',
					method: "POST",
				}, this.callback)
				
			},
			async callback(res) {
				if (res.status == 0) {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					return;
				}
				let {
					access_path,
					storage_type,
					savepath,
					path_name,
					name,
					size,
					ext,
					saveName
				} = res.file
				let _path = access_path

				if (ext == 'mp3' || 'm4a' || 'wma' || 'MP3') {
					this.audio_modle_src = _path
					this.audio_tmp_src = _path
						if(this.video_modle_src){
							this.deleteItem(2,2,false)
						}
				} else {
					this.video_tmp_src = _path
					this.video_modle_src = _path
					if(this.audio_modle_src){
						this.deleteItem(1,1,false)
					}
				}
				this.modleSrc = _path
				this.tmpSrc = _path
				size = changeLimt(size)
				this.dataInfo = {
					name,
					size,
					storage_type,
					savename: storage_type == 1 ? path_name : saveName
				}
				let params = {
					flag: this.blessData.orderId ? 'isEdit' : 'isAdd',
					type: this.isVoice,
					url: this.dataInfo.savename,
					storageType: storage_type,
					address: _path,
					audio_length: this.audio_length ? this.audio_length : '',
					ext: ext,
					name,
					size
				}
				if (this.blessData.orderId) {
					let _params = {
						orderId: this.blessData.orderId,
						type: this.isVoice,
						url: _path,
						storageType: storage_type,
						address: _path,
					}
					const {
						status,
						message
					} = await this.$request('Blessing/Applets/blessingSave', _params)
					console.log(status, 'save')
					if (status == 1) {
						uni.showToast({
							title: message
						})
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							})
						}, 1500)
					} else {
						uni.showToast({
							title: message,
							icon: 'none'
						})
					}
				}
				uni.setStorageSync('blessData', JSON.stringify(params))
				this.isSave = true
			},

			// 删除
			async deleteItem(type,isVoice,isShowTip = true) {
				if ((type == 2 && isVoice == 2) || (type == 1) && isVoice == 1) {
					let obj = {
						storage_type: this.dataInfo.storage_type,
						url: this.dataInfo.savename
					}
					try {
						const res = await this.request('Blessing/Applets/deleteBlessing', obj)
						if (res.status == 1) {
							if(isShowTip){
								uni.showToast({
									title: '删除成功',
								})
							}
							if(type == 2){
								this.audio_tmp_src = '';
								this.audio_modle_src = ''
							}else {
								this.video_tmp_src = '';
								this.video_modle_src = ''
							}
							this.tmpSrc = '';
							this.modleSrc = '';
							this.dataInfo = {}
							this.audio_params = {}
							this.isSave = false
							this.isPlay = true
						}
						uni.removeStorageSync('blessData')
					} catch (err) {
						console.log(err)
					}
				}
			}
		
		}
	}
</script>

<style lang="scss" scoped>
	@import './record-audio.scss';

	.blessingPage {
		width: 100%;
		height: 100vh;
		position: relative;

		.audio_class {
			width: 100%;

			// display: flex;
			// justify-content: space-around;
			.btn_style {
				color: #fff;
				font-size: 28rpx;
			}

		}

		.audio_style {
			display: flex;
			align-items: center;
			justify-content: space-around;
		}

		.audio_info {
			display: flex;
			flex-direction: column;
			width: 90%;
			margin: 20rpx auto;

		}

		.audio_content {
			border: 1rpx solid #ccc;
			width: 90%;
			margin: 30rpx auto;

			.audio_pay {
				display: flex;
				height: 190rpx;
				width: 90%;
				box-sizing: border-box;
				align-items: center;
				margin: 30rpx auto;

				.audio_play {
					height: 80rpx;
					width: 80rpx;
				}

				.audio_pic {
					flex: 1;
					flex-shrink: 0;
					height: 100%;
				}
			}
		}

		.luzhi_style {
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translateX(-50%) translateY(-50%);
			width: 250rpx;
			height: 160rpx;
			background-color: #eee;
			border-radius: 50rpx;
		}

		.circle_style {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin-top: 30rpx;

			.audio_text {
				display: inline-block;
				font-size: 24rpx;
				color: #fff;
				margin-top: 10rpx;
			}
		}

		.c_del {
			background-color: #f56c6c;
		}

		.c_play {
			background-color: #e6a23c;
		}

		.c_save {
			background-color: #67c23a;
		}

		.c_record {
			background-color: #409eff;
		}

		.select_audio {
			display: flex;
			justify-content: space-around;
		}

		.audio_file {
			padding-left: 20rpx;
			box-sizing: border-box;
			margin-top: 20rpx;
		}

		.audio_name {
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.select_video {
			width: 140rpx;
			height: 140rpx;
			border-radius: 50%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #fff;
			font-size: 28rpx;
		}

		.video_item {
			display: flex;
			justify-content: space-around;
			margin-top: 30rpx;
		}

		.tmpvideo {
			display: flex;
			justify-content: center;
			margin-top: 30rpx;
		}
	}
</style>
